package cputils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Connection;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import common.Utils;

public class CPHMACService {
	
//	private static DateFormat format = new SimpleDateFormat("MM-dd HH:mm:ss");

	public static void main(String[] args) throws IOException {
		CPHMACService service = new CPHMACService();
		//service.writeAicaiDLTHMData("14032");
	//	writeAicaiSSQHMData("2014025");
//		service.writeTaobaoHMData("SSQ","2014028",false);
		/*for (int i = 2014020; i <= 2014028; i++) {
			Thread t = new Thread(new ServiceThread("SSQ",i+"",false));
			t.start();
		}*/
		System.out.println(service.tjHM4Aicai("14032"));
	}

	public Map<String, Map<Integer, Integer>> tjHM4Aicai(String issueNo) throws IOException{
		Map<String, Map<Integer, Integer>> res = new HashMap<String, Map<Integer,Integer>>();
		List<String> list = XmlUtils.getHMData("ac_"+issueNo);
		Map<Integer, Integer> bMap = new HashMap<Integer, Integer>();
		Map<Integer, Integer> aMap = new HashMap<Integer, Integer>();
		for (int i = 1; i <= 35; i++) {
			bMap.put(i, 0);
		}
		for (int i = 1; i <= 16; i++) {
			aMap.put(i, 0);
		}
		for (String s : list) {
			s = XmlUtils.replaceHanzi(s, ",");
			s = s.replaceAll(" ", "");
			String[] sArr = s.split("\\|");
			if (sArr!=null&&sArr.length==2) {
				String[] bArr = sArr[0].split(",");
				String[] aArr = sArr[1].split(",");
				for (int i = 0; i < bArr.length; i++) {
					if (StringUtils.isNotBlank(bArr[i])) {
						int num = Integer.parseInt(bArr[i].trim());
						bMap.put(num, bMap.get(num)+1);
					}
				}
				for (int i = 0; i < aArr.length; i++) {
					if (StringUtils.isNotBlank(aArr[i])) {
						int num = Integer.parseInt(aArr[i].trim());
						aMap.put(num, aMap.get(num)+1);
					}
				}
			}
		}
		res.put("b", bMap);
		res.put("a", aMap);
		Utils.print(issueNo+" line:"+list.size());
		res = XmlUtils.makeMap(res, true);
		return res;
	}
	
	public void writeAicaiSSQHMData(String issueNo){
		writeAicaiHMData("FC_SSQ", issueNo);
	}
	public void writeAicaiDLTHMData(String issueNo){
		writeAicaiHMData("TC_DLT", issueNo);
	}
	public void writeAicaiHMData(String game,String issueNo){
		Utils.print("****AC "+game+" "+issueNo+" HMDetailLinks begin...");
		long b1 = System.currentTimeMillis();
		int total = getTotalPageNum(game, issueNo);
		List<String> idList = new ArrayList<String>();
		for (int i = 1; i <= total; i++) {
			Map<String, String> idMap = readDataAicai(game,issueNo, i);
			idList.addAll(idMap.keySet());
		}
		Utils.print("****AC "+game+" "+issueNo+" HMDetailLinks ok..."+idList.size()+"...time:"+(System.currentTimeMillis()-b1)+"ms");
		Utils.print("****AC "+game+" "+issueNo+" HMData begin...");
		int i = 1;
		long b2 = System.currentTimeMillis();
		StringBuilder cBuilder = new StringBuilder();
		int totalRec = 0;
		long b3 = System.currentTimeMillis();
		for (String id : idList) {
			List<String> list = readDataHMAicai(game,issueNo,id);
			if(i%500==0){
				Utils.print("********AC "+game+" "+issueNo+" HMData..."+(i++)+"("+list.size()+")->"+idList.size());
			}
			for (String con : list) {
				totalRec++;
				con = con.replaceAll(" ", "");
				cBuilder.append(con).append("\r\n");
			}
		}
		Utils.print("****AC "+game+" "+issueNo+" HMData ok..."+totalRec+".time:"+(System.currentTimeMillis()-b3));
		Utils.print("****AC "+game+" "+issueNo+" HMData write begin...");
		XmlUtils.writeFile(cBuilder.toString(), "ac_"+issueNo+".txt", false);
		Utils.print("****AC "+game+" "+issueNo+" finished...users:"+idList.size()+" records:"+totalRec);
	}
	
	private List<String> readDataHMAicai(String game,String issueNo,String id) {
		//String url = "http://www.aicai.com/hemai-"+id+".html";
			String url = "http://www.aicai.com/hm/hmdetail!queryPlanDetailContent.jhtml?"
					+ "planNo="+id+"&game="+game+"&issueNo="+issueNo+"&selectType=MANUAL";
		Connection conn = Jsoup.connect(url);
		Document doc = null;
		try {
			doc = conn.get();
		} catch (HttpStatusException e) {
			e.printStackTrace();
			//XmlUtils.writeLogs(" number: "+issueNo+" is illegal.", CPDataService.class, null);
		} catch (IOException e) {
			e.printStackTrace();
		}
		List<String> resList = new ArrayList<String>();
		Elements div = doc.getElementsByAttributeValue("class", "facont_table");
		if (div.size()>0) {
			Elements tbody =div.get(0).getElementsByTag("tbody");
			Elements tr1 = tbody.get(0).getElementsByAttributeValue("class", "tpleft");
			for (Element e : tr1) {
				//System.out.println(e.ownText());
				resList.add(e.ownText());
			}
		}
		return resList;
	}
	private int getSSQNum(String issueNo){
		return getTotalPageNum("FC_SSQ", issueNo);
	}
	private int getDLTNum(String issueNo){
		return getTotalPageNum("TC_DLT", issueNo);
	}
	private int getTotalPageNum(String game,String issueNo){
//		String url = "http://www.aicai.com/hemai/tcdlt/";
		
		String url = "http://www.aicai.com/hm/hmlottery!hemailPlan.jhtml?&game="+game+""
				+"&issueNo="+issueNo+"&groupSqlBuildType=TOP&version=2&encryptBoolean=true"
				+"&hmActionPageUrl=/hm/hmlottery!hemailPlan.jhtml&current_page=1&showPageSize=30";
		Connection conn = Jsoup.connect(url);
		
		Document doc = null;
		try {
			doc = conn.get();
		} catch (HttpStatusException e) {
			//XmlUtils.writeLogs(" number: "+issueNo+" is illegal.", CPDataService.class, null);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Element e = doc.getElementById("jq_page_total");
		String num = e.attr("value");
		return Integer.parseInt(num);
	}
	private Map<String, String> getSSQData(String issueNo,int current_page){
		return readDataAicai("FC_SSQ", issueNo,current_page);
	}
	private Map<String, String> getDLTData(String issueNo,int current_page){
		return readDataAicai("TC_DLT", issueNo,current_page);
	}
	private Map<String, String> readDataAicai(String game,String issueNo,int current_page) {
		String url = "http://www.aicai.com/hm/hmlottery!hemailPlan.jhtml?&game="+game+""
				+"&issueNo="+issueNo+"&groupSqlBuildType=TOP&version=2&encryptBoolean=true"
				+"&hmActionPageUrl=/hm/hmlottery!hemailPlan.jhtml&current_page="+current_page+"&showPageSize=30";
		Connection conn = Jsoup.connect(url);
		Document doc = null;
		try {
			doc = conn.get();
		} catch (HttpStatusException e) {
			XmlUtils.writeLogs(" number: "+issueNo+" is illegal.", CPDataService.class, null);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Map<String, String> resMap = new HashMap<String, String>();
		Elements elements = doc.getElementsByAttributeValue("class", "table_list");
		Elements tr = elements.get(0).getElementsByTag("tr");
		for (Element element : tr) {
			String id = element.attr("id");
			String id1 = id.substring(id.lastIndexOf("_")+1);
			resMap.put(id1, id1);
		}
		return resMap;
	}
	public Map<String,Object> lastIssuoInfo(String game){
		String url = "http://caipiao.taobao.com//lottery/ajax/get_united_list.htm" +
				"?page="+dataLinkPageNo+"&issue=&lotteryType="+game+"&playType=&commission_rate=-1"+
				"&confidential=1&united_fee=0-0&is_not_full=1&creator=&sort_obj=bonusRatio&sort=desc&change_sort=false"+
				"&lowAmount=0&highAmount=0&from=&onsale=&t="+System.currentTimeMillis();
		Connection conn = Jsoup.connect(url);
		Document doc = null;
		int i = 1;
		while (doc == null) {
			try {
				doc = conn.get();
			} catch (IOException e) {
				//e.printStackTrace();
				++i;
				if (i>10) {
					Utils.print("********("+e.getMessage()+")Try to read 10("+i+") times.");
//					System.exit(0);
				}
				conn = Jsoup.connect(url);
			}
		}
		String resultStr = doc.text();
		Map<String,Object> infoMap = new HashMap<String, Object>();
		JSONObject object = JSONObject.fromObject("{\""+resultStr.substring(resultStr.indexOf("totalItem")));
		infoMap.put("totalItem", object.get("totalItem"));
		infoMap.put("lotteryType", object.get("lotteryType"));
		infoMap.put("totalPage", object.get("totalPage"));
		List<String> issueList = new ArrayList<String>();
		JSONArray arr = object.getJSONArray("issueList");
		for (Object object2 : arr) {
			JSONObject object3 = (JSONObject) object2;
			issueList.add(object3.getString("issue"));
			if (object3.getBoolean("onsale")) {
				infoMap.put("onsaleIssueNo", object3.get("issue"));
			}
		}
		infoMap.put("issueList", issueList);
		return infoMap;
	}

	
	
	
	
	private String getFullOrNotName(int is_not_full){
		String fullOrNotStr = "";
		switch (is_not_full) {
		case 1:
			fullOrNotStr = "notfull";
			break;
		case 2:
			fullOrNotStr = "full";
			break;
		default:
			break;
		}
		return fullOrNotStr;
	}
	
}

class ACServiceThread implements Runnable{
	private String game;
	private String issueNo;
	public ACServiceThread(String game,String issueNo){
		this.game = game;
		this.issueNo = issueNo;
	}
	
	@Override
	public void run() {
		CPHMACService service = new CPHMACService();
		service.writeAicaiHMData(game, issueNo);
	}
	
}
